package scitc.alumni.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import scitc.alumni.model.User;
import scitc.alumni.model.dto.LoginDto;
import scitc.alumni.service.IUserService;
import scitc.alumni.util.JwtUtil;
import scitc.alumni.util.ResponseUtil;

import java.lang.annotation.Retention;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Slf4j
@Tag(name = "用户模块", description = "注册、登录认证、管理等")
@RestController
@RequestMapping("/user")
public class UserController {

    // 引入接口
    @Resource
    private IUserService userService;

    @Resource
    ResponseUtil responseUtil;

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    JwtUtil jwtUtil;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Operation(summary = "获取所有用户信息", description = "所有用户信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "0", description = "用户信息查询成功"),
            @ApiResponse(responseCode = "500", description = "用户信息查询失败")
    })
    @GetMapping("/findAll")
//    public List<User> findAll(){
//        return userService.findAll();
//    }
    public ResponseUtil findAll(){
        return responseUtil.success(userService.findAll());
    }


    @PostMapping("/authorize")
    public ResponseUtil userAuthorize(@RequestBody LoginDto loginDto) {
        try {
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());
            Authentication authentication = authenticationManager.authenticate(auth);
            //存储认证信息，以便在应用程序中调用当前的认证信息
            SecurityContextHolder.getContext().setAuthentication(authentication);

            //给用户颁发令牌和其他必要信息（如：个人信息）
            User user = userService.findUserByUsername(loginDto.getUsername());
            //生成令牌
            String token = jwtUtil.createToken(user.getUsername(), user.getRole());

            Map<String, Object> data = Map.of("token", token, "userinfo", user);
            return responseUtil.success("认证成功", data);

        } catch (UsernameNotFoundException e) {
            return responseUtil.fail(401, "用户名不存在");
        } catch (BadCredentialsException e) {
            return responseUtil.fail(401, "认证失败");
        } catch (Exception e) {
            log.info("认证失败" + e.getMessage());
            return responseUtil.fail(401, "未知错误！");
        }
    }


    @PostMapping("/register")
    public ResponseUtil register(@RequestBody User user) {
        return new ResponseUtil().success("cnm xiaoyang");
    }

}
